package com.guosheng.nettytest.three;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

public class MultiplexerTimeServer implements Runnable {

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private volatile boolean stop;


    /**
     * 初始化多路复用器，绑定监听端口
     * @param port
     */
    public MultiplexerTimeServer(int port){
        try {
            //打开一个选择器，通过调用系统级默认SelectorProvider对象的openSelector方法来创建新的选择器
            selector = Selector.open();
            //打开服务器套接字通道，通过调用系统级默认SelectorProvider
            //对象的openServerSocketChannel方法来创建新的通道
            //新通道的套接字最初是未绑定的，可以接受连接之前，必须通过它的某个套接字的bind方法将其绑定到具体的地址
            serverSocketChannel = ServerSocketChannel.open();
            //调整此通道的阻塞模式，如果为true则此通道被置于阻塞模式，如果为false,则此通道被置于非阻塞模式
            serverSocketChannel.configureBlocking(false);
            /*
             *socket()获取与此通道关联的服务器套接字（ServerSocket）
             * bind()将serverSocket绑定到特定地址（ip地址和端口号）
             * backlog侦听backlog长度
             */
            serverSocketChannel.socket().bind(new InetSocketAddress(port),1024);
            /*
            向给定的选择器注册此通道，返回一个选择键
            此方法首先验证此通道是否打开，以及给定的初始相关操作集是否有效
            如果已向给定的选择器注册了此通道，则在将其相关操作集设置为给定值后，返回表示该注册的选择键
            如果尚未向给定的选择器注册此通道，则在保持适当锁定的同时调用选择器的register方法，返回前将得到的键添加到
            此通道的键集中
             */
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("the time server is start in port :" + port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stop(){
        this.stop = true;
    }

    @Override
    public void run() {
        while(!stop){
            try {
                //选择一组键，其相应的通道已为i/o操作准备就绪
                //timeout如果为正，则在等待某个通道准备就绪时最多阻塞timeout毫秒，如果为0，则无限期的等待
                //必须为非负数
                selector.select(1000);
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectedKeys.iterator();
                SelectionKey key = null;
                while(it.hasNext()){
                    key = it.next();
                    it.remove();
                    try {
                        handleInput(key);
                    } catch (Exception e) {
                        e.printStackTrace();
                        if(key != null){
                            key.cancel();
                            if(key.channel() != null){
                                key.channel().close();
                            }
                        }
                    }
                }
            } catch (Throwable t) {
               t.printStackTrace();
            }
        }
        if(selector != null){
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void handleInput(SelectionKey key) throws IOException{
        if(key.isValid()){
            //处理新接入的请求消息
            //测试此键的通道是否已准备好接受新的套接字连接，不支持返回false
            if(key.isAcceptable()){
                //Accept the new connection
                ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                //add the new connection to the selector
                sc.register(selector,SelectionKey.OP_READ);
            }
            //测试此键是否已准备好进行读取

            if(key.isReadable()){
                //read the data
                SocketChannel sc = (SocketChannel)key.channel();
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int readBytes = sc.read(readBuffer);
                if(readBytes > 0){
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes,"utf-8");
                    System.out.println("the time server is receive the order :" + body);
                    String currentTime = "query time order".equalsIgnoreCase(body) ? String.valueOf(new Date().getTime()):
                            "bad order";
                    doWrite(sc,currentTime);
                }else if(readBytes < 0){
                    //对端链路关闭
                    key.cancel();
                    sc.close();
                }else{
                    //读到0字节，忽略
                }
            }
        }

    }

    public void doWrite(SocketChannel sc ,String message) throws IOException{
        if(message != null && message.trim().length() > 0 ){
            byte[] bytes = message.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            sc.write(writeBuffer);
        }

    }
}
